package com.sailboard.iot.opm.web.controller.company;

import com.github.pagehelper.PageInfo;
import com.sailboard.iot.opm.common.*;
import com.sailboard.iot.opm.dao.entity.*;
import com.sailboard.iot.opm.service.AccountService;
import com.sailboard.iot.opm.service.RateService;
import com.sailboard.iot.opm.service.UserService;
import com.sailboard.iot.opm.service.company.CompanyService;
import com.sailboard.iot.opm.service.impl.RoleService;
import com.sailboard.iot.opm.service.qrcode.OssUtil;
import com.sailboard.iot.opm.utils.StringUtils;
import com.sailboard.iot.opm.utils.Utils;
import com.sailboard.iot.opm.web.controller.AttachmentUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;

/**
 * java类简单作用描述
 *
 * @ProjectName: iot-opm
 * @Package: com.sailboard.iot.opm.web.controller.company
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: 候杰
 * @CreateDate: 2017/12/11 20:27
 * @UpdateUser: Neil.Zhou
 * @UpdateDate: 2017/12/11 20:27
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * Copyright: Copyright (c) 2017
 */
@RestController
@RequestMapping("/v1/api0/")
public class CompanyController {

    @Resource
    CompanyService companyService;

    @Resource
    UserService userService;

    @Resource
    RoleService roleService;

    @Resource
    AccountService accountService;

    @Resource
    RateService rateService;

    private User getCurrent_user(){
        User current_user=new User();
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser != null && currentUser.getPrincipals() != null) {
            String username = currentUser.getPrincipals().toString();
            current_user = userService.getByUsername(username);
        }
        return current_user;
    }

    @RequestMapping(value = "company/detail",method = RequestMethod.POST)
    @ResponseBody
    public  JsonResult getDetail(@RequestParam String companyID){
        if (StringUtils.isBlank(companyID)){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        Company company = companyService.getCompanyById(Long.valueOf(companyID));
        return  new JsonResult(ResultCode.SUCCESS_CODE,ResultCode.SUCCESS_MSG,company);
    }

    @RequestMapping(value = "company/list")
    @ResponseBody
    public DataGrid<Company> companyList(Integer page, Integer rows, Company company) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        User user = this.getCurrent_user();
        if (user.getId()!=1){
            Long companyID = user.getCompanyId();
            Company company1 = companyService.getCompanyByID(String.valueOf(companyID));
            if (company1!=null){
                if(company1.getLeader().equals(user.getId())){
                    company.setBelongCompany(companyID);
                }else{
                    company.setFounder(user.getId());
                }
            }else {
                return null;
            }
        }
        PageInfo pageInfo = companyService.getCompanyList(page, rows, company);
        return new DataGrid(pageInfo);
    }

    @RequestMapping(value = "company/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(Company company) {
        if(company == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(company.getName())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "公司名称不能为空");
        }
        if(!StringUtils.isBlank(company.getBankCardNumber())) {
            if (!Utils.isBankCard(company.getBankCardNumber())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "银行卡格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getWechatAccount())) {
            if (!Utils.isWeChat(company.getWechatAccount())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "微信账号格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getAlipayAccount())) {
            if (!Utils.isAlipay(company.getAlipayAccount())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "支付宝账号格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getEmail())) {
            if (!Utils.isEmail(company.getEmail())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "邮箱格式不正确");
            }
        }
        if (!Utils.checkMobile(String.valueOf(company.getMobile()))){
            return  new JsonResult(ResultCode.PARAM_ERROR_CODE, "手机号格式不正确");
        }
        if(companyService.getCompanyByName(company.getName()) != null){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该公司名称已存在");
        }
        if(userService.getUserByMobile(String.valueOf(company.getMobile())) != null){//手机号为负责人的手机号所以要到用户表中去重。
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该手机号已存在");
        }
        if(companyService.getCompanyBySocialCode(company.getSocialCode()) != null){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该社会信用代码已存在");
        }
        //统一社会信用编码校验
        if(company.getSocialCode().length() < 18){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "社会信用代码不足18位，请核对后再输！");
        }
        if(!Utils.isCreditCode(company.getSocialCode()).equals("true")&&!Utils.isOrganizationCertificate(company.getSocialCode())){
            if(company.getType()== Integer.valueOf(2)){//合作伙伴也可以是身份证号。
                if(!Utils.isValidIdNo(company.getSocialCode())){
                    return new JsonResult(ResultCode.PARAM_ERROR_CODE, Utils.isCreditCode(company.getSocialCode()));
                }
            }else{
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, Utils.isCreditCode(company.getSocialCode()));
            }

        }


        //把公司的负责人set到user表中
        User user = new User();
        user.setRealName(company.getLeaderName());
        user.setUsername(company.getSocialCode());
        user.setMobile(String.valueOf(company.getMobile()));
        user.setEmail(company.getEmail());
        user.setStatus((byte)Constants.USER_STATUS_ENABLE);
        user.setPassword("111111");//初始化密码为6个1
        String passowrd = user.getPassword().trim();
        String salt = Utils.generateSalt();
        user.setSalt(salt);
        user.setPassword(Utils.encryptPassword(salt, passowrd));
        user.setCompanyName(company.getName());

        boolean isSuccessUser = userService.addUser(user);
        User userTemp = userService.getByUsername(user.getUsername());

        //生成平台账户信息。
        Account account = new Account();
        account.setName(company.getName() + "的账户");
        account.setUserName(company.getName());
        account.setBankCardNumber(company.getBankCardNumber());
        account.setCreaterId(Long.valueOf(this.getCurrent_user().getId()));
        account.setCreater(this.getCurrent_user().getRealName());
        account.setStatus(Byte.valueOf("1"));
        account.setBalance(BigDecimal.ZERO);
        account.setRecharge(BigDecimal.ZERO);
        account.setProfit(BigDecimal.ZERO);
        account.setInternet(BigDecimal.ZERO);
        account.setBankCardNumber(company.getBankCardNumber());
        boolean isSuccessAccount = accountService.addAccount(account);
        Account accountTemp = accountService.getAccountByName(company.getName() + "的账户");

        //添加角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userTemp.getId());
        userRole.setRoleId(roleService.getRoleByIsMgrAndType("0",String.valueOf(company.getType())).getId());
        roleService.addUserRole(userRole);

        company.setLeader(userTemp.getId());
        company.setFounder(getCurrent_user().getId());//把founder设置为添加者的Id
        company.setBelongCompany(getCurrent_user().getCompanyId());//把B设置为添加者的companyId
        boolean isSuccess = companyService.addCompany(company);
        userTemp.setCompanyId(companyService.getBySocialCode(company.getSocialCode()).getId());
        userService.updateUser(userTemp);

        accountTemp.setUserId(companyService.getBySocialCode(company.getSocialCode()).getId());
        accountService.updateAccount(accountTemp);
        return (isSuccess && isSuccessUser&&isSuccessAccount) ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping("upload")
    @ResponseBody
    public JsonResult upload(@RequestParam("agreementfile") MultipartFile file){
        String oriname= file.getOriginalFilename();
        boolean flag= AttachmentUtil.checkAttachments("dataUploadFile",oriname);
        if(!flag){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "上传文件非法");
        }
        String fileNameNew=AttachmentUtil.saveAttachments(file,oriname);
        if(StringUtils.isBlank(fileNameNew)){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "附件上传失败");
        }
        return new JsonResult(ResultCode.SUCCESS_CODE, oriname+"_"+fileNameNew);
    }
    @RequestMapping(value = "company/edit")
    @ResponseBody
    public JsonResult edit(Company company) {
        if(company == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(company.getName())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "公司名称不能为空");
        }
        if(userService.getOtherUserByMobile(String.valueOf(company.getMobile()),company.getLeader()) != null){//手机号为负责人的手机号所以要到用户表中去重。
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该手机号已存在");
        }
        if(companyService.getOtherCompanyByName(company.getName(),String.valueOf(company.getId())) != null){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该公司名称已存在");
        }
        if(companyService.getOtherCompanyBySocialCode(company.getSocialCode(),String.valueOf(company.getId())) != null){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该公司信用代码已存在");
        }
        if(!StringUtils.isBlank(company.getBankCardNumber())) {
            if (!Utils.isBankCard(company.getBankCardNumber())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "银行卡格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getWechatAccount())) {
            if (!Utils.isWeChat(company.getWechatAccount())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "微信账号格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getAlipayAccount())) {
            if (!Utils.isAlipay(company.getAlipayAccount())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "支付宝账号格式不正确");
            }
        }
        if(!StringUtils.isBlank(company.getEmail())) {
            if (!Utils.isEmail(company.getEmail())){
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "邮箱格式不正确");
            }
        }
        if (!Utils.checkMobile(String.valueOf(company.getMobile()))){
            return  new JsonResult(ResultCode.PARAM_ERROR_CODE, "手机号格式不正确");
        }
        //统一社会信用编码校验
        if(company.getSocialCode().length() < 18){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "社会信用代码不足18位，请核对后再输！");
        }
        if(!Utils.isCreditCode(company.getSocialCode()).equals("true")&&!Utils.isOrganizationCertificate(company.getSocialCode())) {
            if (company.getType() == Integer.valueOf(2)) {//合作伙伴也可以是身份证号。
                if (!Utils.isValidIdNo(company.getSocialCode())) {
                    return new JsonResult(ResultCode.PARAM_ERROR_CODE, Utils.isCreditCode(company.getSocialCode()));
                }
            } else {
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, Utils.isCreditCode(company.getSocialCode()));
            }
        }

        //把公司的负责人set到user表中
        User user = new User();
        user.setId(company.getLeader());
        user.setRealName(company.getLeaderName());
        user.setUsername(company.getSocialCode());
        user.setStatus((byte)Constants.USER_STATUS_ENABLE);
        user.setPassword("111111");//初始化密码为6个1
        String passowrd = user.getPassword().trim();
        String salt = Utils.generateSalt();
        user.setSalt(salt);
        user.setPassword(Utils.encryptPassword(salt, passowrd));
        boolean isSuccessUser = userService.updateUser(user);

        //添加角色
        UserRole role = roleService.getUserRoleByUserID(user.getId());
        if(role==null){
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleService.getRoleByIsMgrAndType("0",String.valueOf(company.getType())).getId());
            roleService.addUserRole(userRole);
        }else{
            role.setUserId(user.getId());
            role.setRoleId(roleService.getRoleByIsMgrAndType("0",String.valueOf(company.getType())).getId());
            roleService.updateUserRole(role);
        }
        company.setLeader(user.getId());
        boolean isSuccess = companyService.updateCompany(company);
        return (isSuccess && isSuccessUser) ? JsonResult.success() : JsonResult.error();
    }


    @RequestMapping(value = "company/delete")
    @ResponseBody
    public JsonResult delete(String ids,String leaders) {
        //删除公司对应的人员
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccessCompany = companyService.batchDelCompany(ids);
        //删除公司对应的人员
        if(StringUtils.isEmpty(leaders)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.batchDelUser(leaders);
        return (isSuccess&&isSuccessCompany) ? JsonResult.success() : JsonResult.error();
    }

    //批量禁用公司
    @RequestMapping(value = "company/batchDisable")
    @ResponseBody
    public JsonResult batchDisable(String ids,String leaders) {
        //禁用公司
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccessCompany = companyService.batchDisableCompany(ids);
        //禁用公司对应的人员
        if(StringUtils.isEmpty(leaders)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.batchDisableUser(leaders);
        return (isSuccess&&isSuccessCompany) ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    //批量启用公司
    @RequestMapping(value = "company/batchEnable")
    @ResponseBody
    public JsonResult batchEnable(String ids,String leaders) {
        //启用公司
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccessCompany = companyService.batchEnableCompany(ids);
        //启用公司对应的人员
        if(StringUtils.isEmpty(leaders)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.batchEnableUser(leaders);
        return (isSuccess&&isSuccessCompany) ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    //启用公司
    @RequestMapping(value = "company/enable", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult enable(Long id,Long leader) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccessCompany = companyService.updateCopmanyStatus(id, Constants.COMPANY_STATUS_ENABLE);
        if(leader == null || leader <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.updateUserStatus(leader, Constants.USER_STATUS_ENABLE);
        return (isSuccessCompany&&isSuccess) ? JsonResult.success() : JsonResult.error();
    }

    //禁用公司
    @RequestMapping(value = "company/disable", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disable(Long id,Long leader) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccessCompany = companyService.updateCopmanyStatus(id, Constants.COMPANY_STATUS_DISABLE);
        if(leader == null || leader <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = userService.updateUserStatus(leader, Constants.USER_STATUS_DISABLE);
        return (isSuccessCompany&&isSuccess) ? JsonResult.success() : JsonResult.error();
    }



    @RequestMapping(value = "company/bindRole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult bindRole(Long companyId,Long leader, String roleIds) {
        if(companyId == null || companyId <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }

        if(leader == null || leader <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        userService.bindRole(leader, roleIds);
        return companyService.bindRole(companyId, roleIds);
    }

    @RequestMapping(value = "company/roles", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult companyRoles(Long companyId) {
        if(companyId == null || companyId <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        List<Role> list = roleService.getCompanyRoles(companyId);
        return new JsonResult<>(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, list);
    }

    /**
     * 平台公司获得代理商的费率
     * @param companyId
     * @return
     */
    @RequestMapping(value = "company/getAgentRate", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getAgentRate(Long companyId) {
        if(companyId == null || companyId <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        Rate rate = rateService.getRateByCompanyID(companyId);
        return new JsonResult<>(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, rate);
    }

    //绑定代理商的费率
    @RequestMapping(value = "company/bindAgentRate", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult bindAgentRate(Rate rate) {
        if(rate == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }if(!Utils.isNumber(String.valueOf(rate.getInternetAccount()))){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请输入正确的网间账户额度");
        }
        if(!Utils.isNumber(String.valueOf(rate.getPlatformRate()))){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请输入正确的平台使用费率");
        }
        if(!Utils.isNumber(String.valueOf(rate.getServiceGuarantee()))){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请输入正确的服务保障金费率");
        }
        boolean isSuccess ;
        if (rate.getId()==null){
            isSuccess = rateService.insertRateSelective(rate);
        }else {
            isSuccess = rateService.updateRateSelective(rate);
        }
        return isSuccess?JsonResult.success():JsonResult.error();
    }

    /**
     * 列出所有代理商的总情况
     * @param page
     * @param rows
     * @param company
     * @return
     */
    @RequestMapping(value = "company_agent_Spy/list", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<CompanySpy> company_agent_Spy_List(Integer page, Integer rows, CompanySpy company) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        User user = this.getCurrent_user();
        if (user.getId()!=1) {
            Long companyID = user.getCompanyId();
            Company company1 = companyService.getCompanyByID(String.valueOf(companyID));
            if (company1 != null) {
                if (company1.getLeader().equals(user.getId())) {
                    company.setCompanyBelong(String.valueOf(companyID));
                } else {
                    company.setCompanyFounder(String.valueOf(user.getId()));
                }
            } else {
                return null;
            }
        }
        PageInfo pageInfo = companyService.getCompany_Agent_Spy_List(page, rows, company);
        return new DataGrid(pageInfo);
    }

    /**
     * 列出代理商的合作伙伴
     * @param page
     * @param rows
     * @param company
     * @return
     */
    @RequestMapping(value = "company_agent_Spy/list_partner", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<CompanySpy> list_Partner(Integer page, Integer rows, Company company) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        PageInfo pageInfo = companyService.getCompanyList(page, rows, company);
        pageInfo.getList();
        return new DataGrid(pageInfo);
    }


    @RequestMapping(value = "company/getProfitRule", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getRateByPartnerId(Long partnerId){
            Rate rate = rateService.getRateByPartnerID(partnerId);
        return new JsonResult<>(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, rate);
    }
    //保存收益规则设置。
    @RequestMapping(value = "company/saveProfitRule", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult saveProfitRule(Rate rate){
        rate.setType(Byte.valueOf("2"));
        rate.setAgentId(this.getCurrent_user().getCompanyId());
        if(rate.getProfitRule().compareTo(BigDecimal.ZERO) == -1 || rate.getProfitRule().compareTo(BigDecimal.valueOf(100)) ==1){
            return new JsonResult(ResultCode.ERROR_CODE,"请输入0-100以内的整数");
        }
        boolean isSuccess;
        if(rate.getId() != null){
             isSuccess = rateService.updateRateSelective(rate);
        }else{
            isSuccess = rateService.insertRateSelective(rate);
        }
        return isSuccess ? JsonResult.success():JsonResult.error();
    }

    @RequestMapping("deletAgreementFile")
    @ResponseBody
    public JsonResult deletAgreementFile(String agreementPath, String agreementName,String companyId, HttpServletRequest request, HttpServletResponse response){
        String filePath= SystemCodeConstants.STATIC_FILE_URL+ File.separator+agreementPath;//OSS服务器路径
        //String filePath= SystemCodeConstants.STATIC_FILE_URL+ "/"+agreementPath;//本地测试用
        if(!StringUtils.isBlank(filePath)){
            if(OssUtil.isFileExist(filePath)){
                OssUtil.deleteFile(filePath);
                companyService.clearCompanyAgreement(Long.valueOf(companyId));
            }else{
                return new JsonResult(ResultCode.PARAM_ERROR_CODE, "删除失败,文件未找到！");
            }
        }else{
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "删除失败,文件未找到！");
        }
        return new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG);
    }
}
